package com.dyna.chat.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import com.dyna.chat.dao.MessageDao;
import com.dyna.chat.dao.MessageMarkDao;
import com.dyna.chat.domain.entity.Message;
import com.dyna.chat.domain.entity.MessageMark;
import com.dyna.chat.domain.req.msg.ChatMessageReq;
import com.dyna.chat.domain.resp.msg.ChatMessageResp;
import com.dyna.chat.event.MessageSendEvent;
import com.dyna.chat.service.ChatService;
import com.dyna.chat.service.MessageAdapter;
import com.dyna.core.utils.SecurityUtil;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ChatServiceImpl implements ChatService {

    @Resource
    private MessageDao messageDao;
    @Resource
    private MessageMarkDao messageMarkDao;
    @Resource
    private ApplicationEventPublisher applicationEventPublisher;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ChatMessageResp sendMsg(ChatMessageReq request) {
        //检查消息是否允许被发送，是否被对方拉黑、是否被移除群聊
        Long uid = Convert.toLong(SecurityUtil.getUserId());
        Message msg = MessageAdapter.buildMsgSave(request, uid);
        msg.setContent((String) request.getBody());
        messageDao.save(msg);
        applicationEventPublisher.publishEvent(new MessageSendEvent(this, msg.getId()));
        return getMsgResp(msg, uid);
    }

    @Override
    public ChatMessageResp getMsgResp(Long msgId, Long receiveUid) {
        Message msg = messageDao.getById(msgId);
        return getMsgResp(msg, receiveUid);
    }

    @Override
    public ChatMessageResp getMsgResp(Message message, Long receiveUid) {
        return CollUtil.getFirst(getMsgRespBatch(Collections.singletonList(message), receiveUid));
    }

    public List<ChatMessageResp> getMsgRespBatch(List<Message> messages, Long receiveUid) {
        if (CollectionUtil.isEmpty(messages)) {
            return new ArrayList<>();
        }
        //查询消息标志
        List<MessageMark> msgMark = messageMarkDao.getValidMarkByMsgIdBatch(messages.stream().map(Message::getId).collect(Collectors.toList()));
        return MessageAdapter.buildMsgResp(messages, msgMark, receiveUid);
    }

}
